package com.unitd.base.frame.plugin.log.factory;

import com.unitd.base.frame.plugin.log.LogSucceed;
import com.unitd.base.frame.plugin.log.LogType;
import com.unitd.base.frame.spring.SpringContextHolder;
import com.unitd.base.frame.util.ExceptionUtil;
import com.unitd.base.module.test.mybatis.mapper.OperationLogMapper;
import com.unitd.base.module.test.po.OperationLog;
import lombok.extern.slf4j.Slf4j;

import java.util.TimerTask;

/**
 * 日志操作任务创建工厂
 *
 * @author Hudan
 * @version 1.0
 * @filename LogFactory.java
 * @copyright www.unitd.com
 * @date 2020-06-29
 */
@Slf4j
public class LogTaskFactory {

    private static OperationLogMapper operationLogMapper = SpringContextHolder.getBean(OperationLogMapper.class);

    /**
     * 产生业务日志
     *
     * @param userId        产生业务日志的用户
     * @param bussinessName 业务名称
     * @param clazzName     产生日志的类名
     * @param methodName    产生日志的方法名
     * @param msg           业务日志详情
     * @return 日志任务
     */
    public static TimerTask bussinessLog(final Long userId, final String bussinessName, final String clazzName, final String methodName, final String msg) {
        return new TimerTask() {
            @Override
            public void run() {
                OperationLog operationLog = LogFactory.createOperationLog(
                        LogType.BUSSINESS, userId, bussinessName, clazzName, methodName, msg, LogSucceed.SUCCESS);
                try {
                    operationLogMapper.insert(operationLog);
                } catch (Exception e) {
                    log.error("创建业务日志异常!", e);
                }
            }
        };
    }

    /**
     * 产生异常日志
     *
     * @param userId    产生异常日志的用户
     * @param exception 异常详情
     * @return 日志任务
     */
    public static TimerTask exceptionLog(final Long userId, final Throwable exception) {
        return new TimerTask() {
            @Override
            public void run() {
                String msg = ExceptionUtil.getExceptionMsg(exception);
                OperationLog operationLog = LogFactory.createOperationLog(
                        LogType.EXCEPTION, userId, "", null, null, msg, LogSucceed.FAIL);
                try {
                    operationLogMapper.insert(operationLog);
                } catch (Exception e) {
                    log.error("创建异常日志异常!", e);
                }
            }
        };
    }
}